{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from docx import Document\n",
    "from docx.oxml.ns import qn\n",
    "from docx.oxml.shape import CT_Picture\n",
    "from docx.image.image import Image\n",
    "from docx.parts.image import ImagePart\n",
    "from PIL import Image\n",
    "from io import BytesIO\n",
    "import re\n",
    "import os\n",
    "import shutil\n",
    "import win32com.client\n",
    "\n",
    "\n",
    "docx_name=[\"教学内容分析\", \"学情分析\", \"教学目标\", \"教学重难点\", \"教学准备\", \"教学方法\",\"教学过程设计\", \"教学环节\", \"教学活动\", \"学习评价\", \"作业设计\", \"板书设计\"]\n",
    "category_name = [\n",
    "    \"教学内容分析\",\"教材分析\",\"内容分析\",\"教学内容\",\n",
    "    \"学情分析\",\"学习者分析\",\n",
    "    \"教学目标\",\"学习目标\",\n",
    "    \"教学重难点\",\"教学重点\",\"教学难点\",\n",
    "    \"教学准备\",\"教学用具\",\n",
    "    \"教学方法\",\n",
    "    \"教学过程\",\n",
    "    \"教学环节\",\n",
    "    \"教学活动\",\n",
    "    \"学习评价\",\"学习效果评价设计\",\n",
    "    \"作业设计\",\"布置作业\", \"课时作业\",\"课后作业\",\n",
    "    \"板书设计\"\n",
    "]\n",
    "category_map = {\n",
    "    \"教学内容分析\":0,\"教材分析\":0,\"内容分析\":0,\"教学内容\":0,\n",
    "    \"学情分析\":1,\"学习者分析\":1,\n",
    "    \"教学目标\":2,\"学习目标\":2,\n",
    "    \"教学重难点\":3,\"教学重点\":3,\"教学难点\":3,\n",
    "    \"教学准备\":4,\"教学用具\":4,\n",
    "    \"教学方法\":5,\n",
    "    \"教学过程\":6,\n",
    "    \"教学环节\":7,\n",
    "    \"教学活动\":8,\n",
    "    \"学习评价\":9,\"学习效果评价设计\":9,\n",
    "    \"作业设计\":10,\"布置作业\":10, \"课时作业\":10,\"课后作业\":10,\n",
    "    \"板书设计\":11\n",
    "}\n",
    "def judge_category(text):\n",
    "    result = -1\n",
    "    for i in range(len(category_name)):\n",
    "        if re.search(category_name[i],text) != None:\n",
    "            return category_map[category_name[i]]#返回类别标号\n",
    "        else:\n",
    "            result = -1\n",
    "    return result\n",
    "\n",
    "\n",
    "def get_picture(document: Document, paragraph):\n",
    "    \"\"\"\n",
    "\tdocument 为文档对象\n",
    "\tparagraph 为内嵌图片的段落对象\n",
    "    \"\"\"\n",
    "    result_list=[]\n",
    "    img_list = paragraph._element.xpath('.//pic:pic') \n",
    "    if len(img_list)==0 or not img_list:\n",
    "        return\n",
    "    for i in range(len(img_list)):\n",
    "        img: CT_Picture = img_list[i]\n",
    "        embed = img.xpath('.//a:blip/@r:embed')[0]\n",
    "        related_part: ImagePart = document.part.related_parts[embed]\n",
    "        image: Image = related_part.image\n",
    "        result_list.append(image)\n",
    "    return result_list\n",
    "\n",
    "\n",
    "def save_docx(docx_path):\n",
    "    path = os.path.join(docx_path, docx_path + \".docx\")\n",
    "    docin = Document(path)\n",
    "    doc = Document()\n",
    "    is_firstparagraph = 1\n",
    "    for paragraph in docin.paragraphs:\n",
    "        image_list = get_picture(docin, paragraph)#判断该段落是否存在图片\n",
    "        category = judge_category(paragraph.text)\n",
    "        if is_firstparagraph == 1 and category == -1:\n",
    "             continue\n",
    "        else:\n",
    "            if category != -1 :\n",
    "                if is_firstparagraph == 1:\n",
    "                    save_category = category\n",
    "                else:\n",
    "                    #判断文件是否已经存在，若存在这将两个文本合并\n",
    "                    save_path = os.path.join(docx_path, docx_name[save_category],docx_name[save_category] + \".docx\")\n",
    "                    if not os.path.exists(save_path):#如果文件不存在，则创建相应的文件夹\n",
    "                        os.makedirs(os.path.join(docx_path, docx_name[save_category]),exist_ok=True)\n",
    "                        doc.save(save_path)\n",
    "                    else:\n",
    "                        doc_exist = Document(save_path)\n",
    "                        # 复制第二个文档的内容到合并后的文档\n",
    "                        for element in doc.element.body:\n",
    "                            doc_exist.element.body.append(element) \n",
    "                        doc_exist.save(save_path)\n",
    "                    save_category = category\n",
    "                    doc = Document()\n",
    "            else:\n",
    "                new_paragraph =doc.add_paragraph()\n",
    "                new_paragraph.alignment = paragraph.alignment\n",
    "                for run in paragraph.runs:\n",
    "                    new_run = new_paragraph.add_run(run.text)\n",
    "                    # 复制文本运行的字体格式 \n",
    "                    new_run.font.name = ''\n",
    "                    # font_name = run.font.name\n",
    "                    new_run.element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')\n",
    "                    new_run.font.size = run.font.size\n",
    "                    new_run.font.bold = run.font.bold\n",
    "                if image_list:\n",
    "                    for image in image_list:\n",
    "                        if image:\n",
    "                            # 二进制内容\n",
    "                            blob = image.blob\n",
    "                            # 读入图片\n",
    "                            doc.add_picture(BytesIO(blob))\n",
    "            is_firstparagraph = 0\n",
    "    #保存最后一个类别\n",
    "    #判断文件是否已经存在，若存在则将两个文本合并\n",
    "    save_path = os.path.join(docx_path, docx_name[save_category],docx_name[save_category] + \".docx\")\n",
    "    if not os.path.exists(save_path):#如果文件不存在，则创建相应的文件夹\n",
    "        os.makedirs(os.path.join(docx_path, docx_name[save_category]),exist_ok=True)\n",
    "        doc.save(save_path)\n",
    "    else:\n",
    "        doc_exist = Document(save_path)\n",
    "        # 复制第二个文档的内容到合并后的文档\n",
    "        for element in doc.element.body:\n",
    "            doc_exist.element.body.append(element) \n",
    "        doc_exist.save(save_path)\n",
    "    \n",
    "\n",
    "\n",
    "# if __name__ == \"__main__\":  \n",
    "#     save_docx('《1.圆的认识》_刘淑娟_(河南省市级优课)')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#将文件夹中的.doc文件改为.docx文件并删除doc文件\n",
    "def doc2docx():\n",
    "    # 指定包含.doc文件的文件夹\n",
    "    folder_path =os.getcwd()#获得当前路径\n",
    "\n",
    "    # 创建Word应用程序实例\n",
    "    word = win32com.client.Dispatch('Word.Application')\n",
    "\n",
    "    # 遍历文件夹中的文件\n",
    "    for filename in os.listdir(folder_path):\n",
    "        if filename.endswith('.doc'):\n",
    "            doc_path = os.path.join(folder_path, filename)\n",
    "            docx_path = os.path.join(folder_path, os.path.splitext(filename)[0] + '.docx')\n",
    "\n",
    "            # 打开.doc文件并另存为.docx\n",
    "            doc = word.Documents.Open(doc_path)\n",
    "            doc.SaveAs(docx_path, FileFormat=16)\n",
    "            doc.Close()\n",
    "\n",
    "            # 删除原始的.doc文件\n",
    "            os.remove(doc_path)\n",
    "\n",
    "    # 退出Word应用程序\n",
    "    word.Quit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "###为每一个word文档创建一个以他们的名字命名的文件夹，并将word文档放入文件夹中\n",
    "def word2folder():\n",
    "    # 指定包含Word文件的文件夹路径\n",
    "    source_folder = \"./\" \n",
    "\n",
    "    # 获取源文件夹中的所有Word文件\n",
    "    word_files = [f for f in os.listdir(source_folder) if f.endswith('.docx')]\n",
    "\n",
    "    # 遍历Word文件\n",
    "    for word_file in word_files:\n",
    "        if word_file.endswith('.docx'):#如果是docx文件就处理\n",
    "            # 获取文件名（去掉文件扩展名）\n",
    "            file_name = os.path.splitext(word_file)[0]\n",
    "\n",
    "            # 创建以文件名命名的文件夹\n",
    "            folder_path = os.path.join(source_folder, file_name)\n",
    "            os.makedirs(folder_path, exist_ok=True)\n",
    "\n",
    "            # 移动Word文件到相应的文件夹\n",
    "            source_path = os.path.join(source_folder, word_file)\n",
    "            target_path = os.path.join(folder_path, word_file)\n",
    "            shutil.move(source_path, target_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "word2folder()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 指定要遍历的父文件夹路径\n",
    "parent_folder = os.getcwd()#获得当前路径 \n",
    "\n",
    "# 获取父文件夹中的所有子文件夹\n",
    "subfolders = [f for f in os.listdir(parent_folder) if os.path.isdir(os.path.join(parent_folder, f))]\n",
    "\n",
    "# 遍历每个子文件夹\n",
    "for subfolder in subfolders:#subfolder表示文件名\n",
    "    save_docx(subfolder)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
